package com.unit4science;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.entities.Chart;
import com.entities.Unit;
import com.myadapter.MyGalleryAdapter;
import com.myadapter.MyListAdapter;

public class ConvertActivity extends Activity {

	private static String buffer = "0";
	private final int MAX_LENGTH = 1000;
	
	private Gallery topGallery;
	private MyGalleryAdapter galleryAdapter;
	private View preView;
	private ListView leftListView;
	private ListView rightListView;
	private MyListAdapter leftListAdapter;
	private MyListAdapter rightListAdapter;

	private List<String> categories = new ArrayList<String>();
	private List<String> items = new ArrayList<String>();

	private int mTopPosition;
	private int mLeftPosition;
	private int mRightPosition;

	private Context context;
	private Resources res;
	private TextView leftTextView;
	private TextView rightTextView;
	private TextView leftUnit;
	private TextView rightUnit;
	private Button switcher;
	private LinearLayout softKeyboard;
	private Button btnNo0;
	private Button btnNo1;
	private Button btnNo2;
	private Button btnNo3;
	private Button btnNo4;
	private Button btnNo5;
	private Button btnNo6;
	private Button btnNo7;
	private Button btnNo8;
	private Button btnNo9;
	private Button btnDel;
	private Button btnDot;
	private Button btnSign;
	private Button btnSwap;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		context = getApplicationContext();
		res = context.getResources();

		leftTextView = (TextView) findViewById(R.id.left_textview);
		rightTextView = (TextView) findViewById(R.id.right_textview);
		leftUnit = (TextView) findViewById(R.id.left_unit);
		rightUnit = (TextView) findViewById(R.id.right_unit);
		topGallery = (Gallery) findViewById(R.id.top_gallery);
		leftListView = (ListView) findViewById(R.id.left_listview);
		rightListView = (ListView) findViewById(R.id.right_listview);
		softKeyboard = (LinearLayout) findViewById(R.id.soft_keyboard);
		switcher = (Button) findViewById(R.id.switcher);

		btnNo0 = (Button) findViewById(R.id.no0);
		btnNo1 = (Button) findViewById(R.id.no1);
		btnNo2 = (Button) findViewById(R.id.no2);
		btnNo3 = (Button) findViewById(R.id.no3);
		btnNo4 = (Button) findViewById(R.id.no4);
		btnNo5 = (Button) findViewById(R.id.no5);
		btnNo6 = (Button) findViewById(R.id.no6);
		btnNo7 = (Button) findViewById(R.id.no7);
		btnNo8 = (Button) findViewById(R.id.no8);
		btnNo9 = (Button) findViewById(R.id.no9);
		btnDel = (Button) findViewById(R.id.del);
		btnDot = (Button) findViewById(R.id.dot);
		btnSign = (Button) findViewById(R.id.sign);
		btnSwap = (Button) findViewById(R.id.swap);

		softKeyboard.setVisibility(View.GONE);
		
//		int i = 1;
		for (Chart chart : Main.charts) {
//			Log.i("Chart " + i++, "" + chart.getName());
			categories.add(chart.getName());
//			List<Unit> unitList = chart.getUnits();
//			int j = 1;
//
//			for (Unit unit : unitList) {
//				Log.i("   unit " + j++, "" + unit.getName());
//			}
		}
				
		// load units cua chart 0 len ListView	
		for (Unit unit : Main.getUnitListFromChartAtIndex(0)) {
			items.add(unit.getName()+unit.getShortName());
		}
		
		// Dieu khien ban phim ao va xac dinh lai vi tri duoc chon trong ListView
		switcher.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (softKeyboard.getVisibility() == View.VISIBLE) {
					softKeyboard.setVisibility(View.GONE);
					switcher.setBackgroundDrawable(res
							.getDrawable(R.drawable.up));
					leftListView.post(new Runnable() {
						@Override
						public void run() {
							leftListView.setSelectionFromTop(mLeftPosition,
									leftListView.getHeight() / 2 - 20);
						}
					});
					rightListView.post(new Runnable() {
						@Override
						public void run() {
							rightListView.setSelectionFromTop(mRightPosition,
									rightListView.getHeight() / 2 - 20);
						}
					});

				} else {
					softKeyboard.setVisibility(View.VISIBLE);
					switcher.setBackgroundDrawable(res
							.getDrawable(R.drawable.down));
					leftListView.post(new Runnable() {
						@Override
						public void run() {
							leftListView.setSelectionFromTop(mLeftPosition,
									leftListView.getHeight() / 2 - 20);
						}
					});
					rightListView.post(new Runnable() {
						@Override
						public void run() {
							rightListView.setSelectionFromTop(mRightPosition,
									rightListView.getHeight() / 2 - 20);
						}
					});
				}// if
			}
		});// onclick
		
		
		
		galleryAdapter = new MyGalleryAdapter(this, R.layout.top_item, categories);
		topGallery.setAdapter(galleryAdapter);

		// thiet lap gia tri duoc chon ban dau cho topGallery
		int topSelect = 0;

		// doi sang gia tri trong Adapter[0..Integer.MAXVALUE]
		// khoi tao cho topgallery
		mTopPosition = ((MAX_LENGTH / categories.size()) / 2)
				* categories.size() + topSelect;
		topGallery.setSelection(mTopPosition);
		
		preView = null; // ghi nho view cu de xoa animation
		topGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			@Override
			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				mTopPosition = getTruePosition(position, categories);
				
				if (preView != null) {
					preView.clearAnimation();
					//preView.setSelected(false);
				}
				v.startAnimation(AnimationUtils.loadAnimation(context,
						R.anim.zoom_in));
				preView = v;
				List<String> newItems = new ArrayList<String>();
				
				// load units cua chart len ListView	
				for (Unit unit : Main.getUnitListFromChartAtIndex(mTopPosition)) {
					newItems.add(unit.getName()+" ("+unit.getShortName()+")");
				}
				items.clear();
				items.addAll(newItems);
				// refresh lai listview
				leftListAdapter.notifyDataSetChanged();
				rightListAdapter.notifyDataSetChanged();

				// settext lai cho 2 don vi
				leftUnit.setText(R.string.text_hint);
				rightUnit.setText(R.string.text_hint);
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		// thiet lap gia tri duoc chon ban dau cho ca 2 listview
		int listSelect = 0;

		// doi sang gia tri trong Adapter[0..Integer.MAXVALUE]
		// khoi tao gia tri cho leftlistview
		mLeftPosition = ((MAX_LENGTH / items.size()) / 2)
				* items.size() + listSelect;
				
		// khoi tao gia tri cho leftListView
		leftListAdapter = new MyListAdapter(this, R.layout.leftlist_item, items);
		leftListView.setAdapter(leftListAdapter);
		leftListView.setSelection(mLeftPosition);
		
		leftListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// Lay chieu dai va chieu rong cua listview
				// chia doi va xac dinh toa do trong tam
				int x = leftListView.getWidth() / 2;
				int y = leftListView.getHeight() / 2;

				// tra ve position cua mot phan tu trong adapter tai toa do
				// (x,y)
				int position = leftListView.pointToPosition(x, y);
				mLeftPosition = position;
				
				// chuyen tu position trong mang [0..Integer.MAXVALUE-1]
				// thanh position trong mang [0..items.size()]
				position = getTruePosition(position, items);

				leftUnit.setText(Html.fromHtml(Main.getChartAtIndex(mTopPosition).getUnit(position).getName()
						+"\n("+Main.getChartAtIndex(mTopPosition).getUnit(position).getShortName()+")"));
				
				// goi ham chuyen doi don vi va cap nhat output cho
				// rightTextview tai day
				updateOutput();
				
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_UP: // bat su kien roi ngon tay khoi man
											// hinh
					leftListView.smoothScrollBy(0, 0);// khong cho listview tiep
														// tuc chay sau khi roi
														// ngon tay khoi ban
														// phim
					break;
				default:
					break;
				}
				return false;
			}
		});
		// khoi tao gia tri cho rightlistview
		mRightPosition = ((MAX_LENGTH / items.size()) / 2)
				* items.size() + listSelect;
		
		// khoi tao gia tri chi rightListView
		rightListAdapter = new MyListAdapter(this, R.layout.rightlist_item, items);
		rightListView.setAdapter(rightListAdapter);
		rightListView.setSelection(mRightPosition);

		rightListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// Lay chieu dai va chieu rong cua listview
				// chia doi va xac dinh toa do trong tam
				int x = rightListView.getWidth() / 2;
				int y = rightListView.getHeight() / 2;

				// tra ve position cua mot phan tu trong adapter tai toa do
				// (x,y)
				int position = rightListView.pointToPosition(x, y);
				mRightPosition = position;

				// chuyen tu position trong mang [0..Integer.MAXVALUE-1]
				// thanh position trong mang [0..items.size()]
				position = getTruePosition(position, items);

				rightUnit.setText(Html.fromHtml(Main.getChartAtIndex(mTopPosition).getUnit(position).getName()
						+"\n("+Main.getChartAtIndex(mTopPosition).getUnit(position).getShortName()+")"));
				// goi ham chuyen doi don vi va cap nhat output cho
				// rightTextview tai day
				updateOutput();
				
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_UP: // bat su kien roi ngon tay khoi man
											// hinh
					rightListView.smoothScrollBy(0, 0); // khong cho listview
														// tiep tuc chay sau khi
														// roi ngon tay khoi man
														// hinh
					break;
				default:
					break;
				}
				return false;
			}
		});

		btnNo0.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(0);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(1);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(2);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(3);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(4);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(5);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo6.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(6);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo7.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(7);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo8.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(8);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnNo9.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateBuffer(9);
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnDot.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean flag = true;
				int i = 0;
				while (i < buffer.length() && flag) {
					if (buffer.charAt(i) == '.') {
						flag = false;
					}
					i++;
				}
				if (flag == true) {
					buffer = buffer + ".";
					leftTextView.setText(buffer);
					updateOutput();
				}			
			}
		});

		btnDel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (buffer.charAt(0) == '-') {
					if (buffer.length() > 2) {
						buffer = buffer.substring(0, buffer.length() - 1);
					} else {
						buffer = "0";
					}
				} else {
					if (buffer.length() > 1) {
						buffer = buffer.substring(0, buffer.length() - 1);
					} else {
						buffer = "0";
					}

				}
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnDel.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				buffer = "0";
				leftTextView.setText(buffer);
				updateOutput();
				return false;
			}
		});

		btnSign.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!buffer.equals("0")) {
					if (buffer.charAt(0) == '-') {
						buffer = buffer.substring(1, buffer.length());
					} else {
						buffer = "-" + buffer;
					}
				}
				leftTextView.setText(buffer);
				updateOutput();
			}
		});

		btnSwap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int temp = mRightPosition;
				mRightPosition = mLeftPosition;
				mLeftPosition = temp;

				leftListView.post(new Runnable() {
					@Override
					public void run() {
						leftListView.setSelectionFromTop(mLeftPosition,
								leftListView.getHeight() / 2 - 20);
					}
				});
				rightListView.post(new Runnable() {
					@Override
					public void run() {
						rightListView.setSelectionFromTop(mRightPosition,
								rightListView.getHeight() / 2 - 20);
					}
				});

				int leftPosition = getTruePosition(mLeftPosition, items);
				int rightPosition = getTruePosition(mRightPosition, items);

				leftUnit.setText(Html.fromHtml(Main.getChartAtIndex(mTopPosition).getUnit(leftPosition).getName()
						+"\n("+Main.getChartAtIndex(mTopPosition).getUnit(leftPosition).getShortName()+")"));
				rightUnit.setText(Html.fromHtml(Main.getChartAtIndex(mTopPosition).getUnit(rightPosition).getName()
						+"\n("+Main.getChartAtIndex(mTopPosition).getUnit(rightPosition).getShortName()+")"));
				updateOutput();
			}
		});

	}// onCreate

	/**
	 * Vi adapter duoc gia lap la mot danh sach co Integer.MAXVALUE phan tu can
	 * phai chuyen doi position trong danh sach tren thanh position trong mang
	 * that voi items.size() phan tu
	 * 
	 * @param position
	 *            [0..Integer.MAXVALUE-1]
	 * @return position [0..items.size()-1]
	 */
	public int getTruePosition(int position, List<String> myList) {
		if (position >= myList.size()) {
			position = position % myList.size();
		}
		return position;
	}

	/**
	 * Cap nhat gia tri dau vao
	 * @param number
	 */
	private void updateBuffer(int number) {
		if (buffer.length() < 13) {
			buffer = buffer.equals("0") ? "" + number : buffer + number;
		}
	}

	/**
	 * Tinh toan va cap nhat gia tri dau ra
	 * @param topPosition
	 */
	private void updateOutput() {
		
		int leftPosition = getTruePosition(mLeftPosition, items);
		int rightPosition = getTruePosition(mRightPosition, items);
		float result = 0;
		
		if (mTopPosition != 21) {
			if (leftPosition == rightPosition) {
				result = new Float(buffer);
			} else {
				result = Main.getChartAtIndex(mTopPosition).convert(leftPosition,
						rightPosition, new Float(buffer));
			}
		} else {// position cua Temperature
			if (leftPosition == rightPosition) {
				result = new Float(buffer);
			} else {
				Float input = new Float(buffer);
				result = input * Main.getChartAtIndex(mTopPosition).convertTemperature(leftPosition, rightPosition);
				
			}
		}	
		rightTextView.setText(""+result);
	}
}
